<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Qiniu\Auth;
use App\Http\Requests;
use App\Property;

class ImageController extends Controller
{

    protected $upManager;
    protected $bucketManager;
    protected $auth;
    protected $token;
    protected $bucketName;


    public function __construct()
    {
        $accessKey = config('app.QNAK');
        $secretKey = config('app.QNSK');
        $this->bucketName = config('app.QNBN');
        $this->upManager = new UploadManager();
        $this->auth = new Auth($accessKey, $secretKey);
        $this->token = $this->auth->uploadToken($this->bucketName);
        $this->bucketManager = new BucketManager($this->auth);

    }



    public function index () {
        $images = $this->bucketManager->listFiles($this->bucketName,'image_');
        $images = $images[0];
        return view('image.index',compact('images'));
    }

    public function storeImage (Request $request) {
        $localImagePaht = 'image_'.$request->input('property_id').'_property_';
        $localImagePaht = uniqid($localImagePaht);
        $realPath = $request->file('image')->getRealPath();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $this->upManager->putFile($this->token, $localImagePaht, $realPath);
        if ($err !== null) {
            var_dump($err);
        } else {
            $p = Property::find($request->input('property_id'));
            $p->coverage_img = $localImagePaht;
            $p->save();

            return redirect(route('property.edit',$p));
        }

    }



}
